package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.getUserInfo(blog);
            this.setBlogLike(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryDetailBlog(Long id) {
        Blog blog = getById(id);
        if(blog==null){
            return Result.fail("笔记不存在");
        }

        this.getUserInfo(blog);
        this.setBlogLike(blog);
        return Result.ok(blog);
    }

    private void setBlogLike(Blog blog) {
        if(UserHolder.getUser() == null){
            return;
        }

        String redisKey = "blog:liked:"+blog.getId();
        Long userId = UserHolder.getUser().getId();

        Double score = stringRedisTemplate.opsForZSet().score(redisKey, userId.toString());

        blog.setIsLike(score!=null);
    }

    /**
     * 判断当前用户是否点过赞
     * @param id
     * @return
     */
    @Override
    public Result isLiked(Long id) {
        //查询Redis中当前用户是否给该笔记点赞过
        String redisKey = "blog:liked:"+id;
        Long userId = UserHolder.getUser().getId();

        Double score = stringRedisTemplate.opsForZSet().score(redisKey, userId.toString());

        if(score==null){
            //没有点赞过，点赞数加1
            boolean success = update().setSql("liked = liked+1").eq("id", id).update();
            if(success){
                //数据库修改成功，给Redis添加记录
                stringRedisTemplate.opsForZSet().add(redisKey,userId.toString(),System.currentTimeMillis());
            }
        }else{
            //如果点赞过，就取消点赞
            boolean success = update().setSql("liked = liked-1").eq("id", id).update();
            if(success){
                //数据库修改成功，给Redis添加记录
                stringRedisTemplate.opsForZSet().remove(redisKey,userId.toString());
            }
        }

        return Result.ok();
    }

    /**
     * 查询点赞top5
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        Set<String> range = stringRedisTemplate.opsForZSet().range(RedisConstants.BLOG_LIKED_KEY+id, 0, 4);
        if(range==null || range.isEmpty()){
            return Result.ok(Collections.emptyList());
        }

        List<Long> top5Id = range.stream().map(Long::valueOf).collect(Collectors.toList());

        String idStr = StrUtil.join(",", top5Id);
        //为了前端的一致性，将先点赞的放在前面，需要进行将返回结果按照点赞ID顺序排序
        List<UserDTO> userDTOS = userService.query()
                .in("id", top5Id)
                .last("order by field(id,"+idStr+")")
                .list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());

        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("笔记保存失败");
        }

        //获取当前用户的粉丝
        List<Follow> followsId = followService.query().eq("follow_user_id", user.getId()).list();
        if(followsId == null || followsId.isEmpty()){
            return Result.ok(blog.getId());
        }

        long curTimeStamp = System.currentTimeMillis();
        for (Follow follow : followsId) {
            String key = "feed:"+follow.getUserId();
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),curTimeStamp);

        }
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryPageBlogFollow(Long lastId, Integer offset) {
        Long userId = UserHolder.getUser().getId();
        String key = "feed:"+userId;

        Set<ZSetOperations.TypedTuple<String>> withScores = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, lastId,offset,3);

        if (withScores==null || withScores.isEmpty()){
            return Result.ok();
        }

        List<Blog> blogs = new ArrayList<>();
        long minTime = System.currentTimeMillis();
        int count=0;
        for (ZSetOperations.TypedTuple<String> withScore : withScores) {
            String id = withScore.getValue();
            Blog blog = getById(Integer.valueOf(id));

            //补充：查询当前笔记作者消息，以及当前用户有无点赞
            getUserInfo(blog);
            setBlogLike(blog);
            blogs.add(blog);

            long score = withScore.getScore().longValue();
            if(score<minTime){
                minTime=score;
                count=0;
            }

            if(score == minTime){
                count++;
            }
        }

        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(count);
        return Result.ok(scrollResult);
    }


    /**
     * 根据blog查询相关用户的用户名和头像
     * @param blog
     */
    private void getUserInfo(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

}
